
<template>
    <div class="app-container">

        <!-- 表格查询 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">

            <el-form-item label="单据时间" prop="lastDay">
                <el-select v-model="queryParams.lastDay" placeholder="请选择单据时间">
                    <el-option
                        label="最近一天"
                        value="1"
                    />
                    <el-option
                        label="最近三天"
                        value="2"
                    />
                    <el-option
                        label="最近一周"
                        value="3"
                    />
                    <el-option
                        label="最近一月"
                        value="4"
                    />
                    <el-option
                        label="最近三月"
                        value="5"
                    />
                    <el-option
                        label="最近半年"
                        value="6"
                    />
                    <el-option
                        label="最近一年"
                        value="7"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="制作时间" prop="requestDate">
                <el-date-picker
                    :clearable="false"
                    v-model="valueTime"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label="业务员" prop="bizUser">
                <el-select v-model="queryParams.bizUser" placeholder="请选择业务员">
                    <el-option
                        v-for="dict in userList"
                        :key="dict.userId"
                        :label="dict.userName"
                        :value="dict.nickName"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="客户名称" prop="clientName">
                <el-input
                    v-model="queryParams.clientName"
                    placeholder="请输入客户名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="报价单号" prop="quotationCode">
                <el-input
                    v-model="queryParams.quotationCode"
                    placeholder="请输入报价单号"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            
            <!-- <el-form-item >
            <el-radio-group v-model="queryParams.poStatusList">
                <el-radio :label="'not_in'">从未交货</el-radio>
                <el-radio :label="'part_in'">部分交货</el-radio>
                <el-radio :label="'all_in'">完全交货</el-radio>
            </el-radio-group>
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
  
        <!-- 表头操作 -->
        <el-row :gutter="10"  class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <!-- <el-col :span="1.8">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleUpload"
                >会员导入</el-button>
            </el-col> -->
            <!-- <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    @click="handleUpdate"
                >修改</el-button>
            </el-col> -->
            <el-col :span="2.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    @click="()=>handleEnable('copy')"
                >复制</el-button>
            </el-col>

            
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-success"
                    size="mini"
                    @click="()=>handleEnable('Y')"
                >作废</el-button>
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-error"
                    size="mini"
                    @click="()=>handleEnable('N')"
                >停用</el-button>
            </el-col> -->
            
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    @click="handleDelete"
                >删除</el-button>
            </el-col>
            <right-toolbar @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格数据 -->
        <vxe-table
            border
            stripe
            v-loading="loading" 
            ref="tableRef"
            size="small"
            header-align="center"
            :row-config="rowConfig"
            :column-config="columnConfig"
            @checkbox-change="checkboxChangeEvent"
            @checkbox-all="checkboxAll"
            @cell-click="cellClickEvent"
            :data="tableDataList"
        >
            <vxe-column type="checkbox" width="80" fixed="left" drag-sort />
            <vxe-column field="clientName" show-overflow="title" align="center" title="客户名称" />
            <vxe-column field="quotationCode" show-overflow="title" align="center" title="销售报价单号" />
            <vxe-column field="contact" show-overflow="title" align="center" title="客户联系人"  />
            <vxe-column field="clientType"  show-overflow="title" align="center" title="客户分类" />
            <vxe-column field="priceLevel" show-overflow="title" align="center" title="价格等级" />
            <vxe-column field="salesMode"  show-overflow="title" align="center" title="销售方式" />
            <!-- <vxe-column field="updateTime" show-overflow="title" align="center" title="含税金额"  /> -->
            <!-- <vxe-column field="updateTime" show-overflow="title" align="center" title="运费"  /> -->
            <vxe-column field="deliveryTime" show-overflow="title" align="center" title="交货日期"  />
            <vxe-column field="deadLine" show-overflow="title" align="center" title="截止日期"  />
            <vxe-column field="settlementTime	" show-overflow="title" align="center" title="结算日期"  />
            <!-- <vxe-column field="updateTime" show-overflow="title" align="center" title="报价制单日期"  /> -->
            <vxe-column field="bizUser" show-overflow="title" align="center" title="业务员"  />
            <vxe-column field="remark" show-overflow="title" align="center" title="备注"  />
            
            <vxe-column width="180" align="center" title="操作" fixed="right">
                <template #default="{ row }">
                    <el-button
                        size="mini"
                        type="text"
                        @click="handleUpdate(row)"
                    >
                        修改
                    </el-button>
                    <!-- <el-button
                    size="mini"
                    type="text"
                    v-if="row.poStatus=='audited'"
                    @click="handleDelete(row)"
                    >删除</el-button> -->
                    <!-- <el-button
                    size="mini"
                    type="text"
                    @click="handleToExamine(row)"
                    >审核</el-button> -->
                    <!-- <el-button
                    size="mini"
                    type="text"
                    @click="handlePrint(row)"
                    >打印</el-button> -->
                </template>
            </vxe-column>
        </vxe-table>

        <!-- 分页 -->
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    
        <!-- 底部表格 -->
        <div class="app-container-footer">
            <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick" :lazy="true">
                <el-tab-pane label="销售报价明细" name="1"><offerDetails :cellId="cellId" :poStatus="bottomTableData" /></el-tab-pane>
                <el-tab-pane label="操作日志" name="2"><baseInfo :cellId="cellId" :poStatus="bottomTableData" /></el-tab-pane>
            </el-tabs>
        </div>
  
        <!-- 新增弹窗 -->
        <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="60%" append-to-body @close="cancel">
          
            <el-form  ref="form" :model="form" :rules="rules" label-width="120px">
                <span class="row_title">审核信息</span>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="销售方式？" prop="bizUser">
                            <el-select v-model="form.bizUser" placeholder="请选择销售方式">
                            <!-- <el-option
                                v-for="dict in userList"
                                :key="dict.userId"
                                :label="dict.userName"
                                :value="dict.nickName"
                            /> -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户名称" prop="clientName">
                            <el-input v-model="form.clientName" placeholder="请输入客户名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户代码？" prop="bizUser">
                            <el-input v-model="form.shopCode" placeholder="请输入客户代码" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="报价单编号" prop="quotationCode">
                            <el-input v-model="form.quotationCode" placeholder="请输入报价单编号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="业务员" prop="bizUser">
                            <el-select v-model="form.bizUser" placeholder="请选择业务员">
                                <el-option
                                    v-for="dict in userList"
                                    :key="dict.userId"
                                    :label="dict.userName"
                                    :value="dict.nickName"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="客户分类" prop="clientType">
                            <el-input v-model="form.clientType" placeholder="请输入客户分类" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <span class="row_title">报价单其他信息</span>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="报价日期？" prop="shopCode">
                            <el-input v-model="form.shopCode" placeholder="请输入代码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="生效时间？" prop="shopName">
                            <el-input v-model="form.shopName" placeholder="请输入名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="失效时间？" prop="shopNickName">
                            <el-input v-model="form.shopNickName" placeholder="请输入昵称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="预计发货时间？" prop="shopCode">
                            <el-input v-model="form.shopCode" placeholder="请输入代码" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="税额？" prop="shopName">
                            <el-input v-model="form.shopName" placeholder="请输入名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="让利后金额？" prop="shopNickName">
                            <el-input v-model="form.shopNickName" placeholder="请输入昵称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
                    </el-form-item>
                </el-row>

                <span class="row_title">单据标注</span>
                <el-row>
                    <el-form-item prop="tag">
                        <el-radio-group v-model="form.tag">
                            <el-radio :label="1">非常重要</el-radio>
                            <el-radio :label="2">重要</el-radio>
                            <el-radio :label="3">较重要</el-radio>
                            <el-radio :label="4">一般</el-radio>
                            <el-radio :label="5">次要</el-radio>
                            <el-radio :label="6">不重要</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-row>
                <el-row>
                    <el-form-item label="？" prop="remark">
                    <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
                    </el-form-item>
                </el-row>


                <!-- <el-row>
                    <el-col :span="6">
                        <el-form-item label="币别" prop="currency">
                            <el-select v-model="form.currency" placeholder="请选择币别">
                            <el-option
                                v-for="dict in dict.type.currency_type"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.label"
                            />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="结算账户" prop="settlementAccounts">
                            <el-input v-model="form.settlementAccounts" placeholder="请输入结算账户" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                    <el-form-item label="SessionKey" prop="sessionKey">
                        <el-input v-model="form.sessionKey" placeholder="请输入SessionKey" />
                    </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="地区信息" prop="shipperArea">
                            <el-input v-model="form.shipperArea" placeholder="请输入地区信息" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="寄件人姓名" prop="shipper">
                            <el-input v-model="form.shipper" placeholder="请输入寄件人姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="寄件人地址" prop="shipperAddress">
                            <el-input v-model="form.shipperAddress" placeholder="请输入寄件人地址" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="寄件人邮箱" prop="shipperPostcode">
                            <el-input v-model="form.shipperPostcode" placeholder="请输入寄件人邮箱" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="寄件人电话" prop="shipperTel">
                            <el-input v-model="form.shipperTel" placeholder="请输入寄件人电话" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="寄件人手机" prop="shipperPhone">
                            <el-input v-model="form.shipperPhone" placeholder="请输入寄件人手机" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="汇率" prop="exchRate">
                            <el-input v-model="form.exchRate" placeholder="请输入汇率" type="number" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
                    </el-form-item>
                </el-row> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" v-if="form.id" @click="submitForm1">保 存</el-button>
                <el-button type="primary" v-if="!form.id" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
  
    </div>
  </template>
  
  <script>
  import { 
    addSaleOffer,
    listSaleOffer,
    delSaleOffer,
    editSaleOffer,
   } from "@/api/mes/sales/saleOffer";
  import { getToken } from "@/utils/auth";
  import { listUser } from "@/api/system/user";
  import baseInfo from "./components/baseInfo.vue";
  import offerDetails from "./components/offerDetails.vue";
  export default {
    name: 'ShopBasic',
    dicts: ['currency_type'],
    components: { 
      baseInfo,
      offerDetails,
    },
    data() {
      return {
        //自动生成编码
        autoGenFlag:false,
        title: '',
        open: false,
        loading: false,
        total: 0,
        form: {},
        rules: {
            shopType:[{ required: true, message: '请输入店铺类型', trigger: 'blur' }],
            shopCode:[{ required: true, message: '请输入店铺编码', trigger: 'blur' }],
            shopName:[{ required: true, message: '请选择店铺名称', trigger: 'blur' }],
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          poCode: null,
          vendorNick: null,
          poStatusList: undefined,
          poCheckStatusList: undefined,
        },
        tableDataList: [],
        vendorList: [],
        warehouseList: [],
        userList: [],
        activeName: '1',
        cellId: null, //当前选中单元格的id
        baseTotal: 0, //采购订单条数
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/mes/md/shop/importData"
        },
        columnConfig: {
          drag: true,
          resizable: true,
          storage: true,
          sortConfig: {
            trigger: 'cell',
            remote: true
          },
          align: 'center',
          headerAlign: 'center'
        },
        rowConfig: {
          drag: true,
          keyField: 'id',
          isHover: true,
          isCurrent: true,
        },
        ids: [], //选中的条目
        bottomTableData: '', //采购订单状态
        valueTime: this.getDefaultDateRange(),
      }
    },
    created() {
      this.getList()
      listUser({ pageNum: 1, pageSize: 9999 }).then(response => {
        this.userList = response.rows;
      })
    },
    methods: {
        getDefaultDateRange() {
            const today = new Date();
            const thirtyDaysAgo = new Date();
            thirtyDaysAgo.setDate(today.getDate() - 30);
            const formatDate = (date) => {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            };
            return [formatDate(thirtyDaysAgo), formatDate(today)];
        },
      getList(){
        this.loading = true;
        this.queryParams.startDate = this.valueTime[0]
        this.queryParams.endDate = this.valueTime[1]
        // this.poCheckStatusList = []
        // this.queryParams.poStatusList = this.queryParams.poStatusList?[this.queryParams.poStatusList]:null
        // this.queryParams.poCheckStatusList = this.queryParams.poCheckStatusList?[this.queryParams.poCheckStatusList]:null
        listSaleOffer(this.queryParams).then(response => {
          this.tableDataList = response.rows;
          this.$nextTick(() => {
            this.$refs.tableRef.setCurrentRow(this.tableDataList[0]);
            // this.bottomTableData = this.tableDataList[0].bottomTableData;
          })
          if(response.rows?.length>0){
            this.cellId = response.rows[0].id;
          }
          this.total = response.total;
          console.log(response);
        }).finally(() => {
          this.loading = false;
        //   this.queryParams.poStatusList = this.queryParams.poStatusList?.join()
        //   this.queryParams.poCheckStatusList = this.queryParams.poCheckStatusList?.join()
        })
      },
      reset(){
        this.form = {};
        this.autoGenFlag = false;
        // this.$refs.form.resetFields();
      },
      handleAdd(){
        this.open = true;
        this.title = '新增';
        this.reset()
        this.$refs["form"].resetFields()
      },
      handleDelete(row){
        if(this.ids.length==0){
          this.$modal.msgError("请选择要删除的数据");
          return;
        }
        const ids = this.ids;
        this.$modal.confirm('是否确认删除该数据项？').then(function() {
          return delSaleOffer(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleUpdate(row){
        console.log(row);
        this.title = '修改';
        this.reset();
        this.open = true;
        this.form = { ...row };
      },
      handleEnable(val){
        if(this.ids.length == 0){
          this.$modal.msgError("请选择数据");
          return;
        }
        this.$confirm('确定要修改吗？').then(() => {
            // batchUpdateStatus({
            //     clientIds: this.ids,
            //     enable: val,
            // }).then(response => {
            //     this.$modal.msgSuccess("修改成功");
            //     this.getList();
            // });
        }) 
      },
      handleToExamine(row){
        console.log(row);
      },
      handleAntiAudit(row){
        console.log(row);
      },
      handleQuery(){
        this.queryParams.pageNum = 1;
        this.getList();
      },
      resetQuery(){
        this.resetForm("queryForm");
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          poCode: null,
          vendorNick: null,
          poStatusList: undefined,
          poCheckStatusList: undefined,
        },
        this.valueTime = this.getDefaultDateRange()
        this.getList();
      },
      submitForm(){
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
                editSaleOffer(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              // this.form.deliveryTime = this.parseTime(this.form.deliveryTime, '{y}-{m}-{d} {h}:{i}:{s}')
              addSaleOffer(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        })
      },
      cancel(){
        this.$refs["form"].resetFields();
        this.open = false;
      },
      cellClickEvent({row}){
        this.cellId = row.id;
        // this.bottomTableData = row.poStatus;
        this.handleClick({name:'1'})
        console.log(row);
      },
      checkboxChangeEvent(checked){
        this.ids = checked.records.map(item => item.id)
        console.log(checked.records, this.ids);
      },
      checkboxAll(checked){
        this.ids = checked.records.map(item => item.id)
        console.log(checked.records, this.ids)
      },
      handleClick(tab, event) {
        switch (tab.name) {
          case '1':
            console.log('基础信息');
            break;
          case '2':
            console.log('2');
            break;
          default:
            break;
        }
      },
      // 订单明细
    //   getBaseInfoList(params={pageNum:1,pageSize:10}){
    //     detailPurchaseOrder(this.cellId, params).then(response => {
    //       this.baseTotal = response.total;
    //       console.log(response);
    //     })
    //   },
      handleUpload(){
        this.upload.title = "数据导入";
        this.upload.open = true;
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      handlePrint(row){
        console.log(row, window.location);
        window.open(window.location.origin + window.location.pathname + '#/printTemplate?poId=' + row.id + '&type=in', '_blank');
      },
      submitForm1(){
        this.$confirm('确定要修改吗？').then(() => {
          editSaleOffer(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
        })
      },
      importTemplate(){
        window.open("/excel_templates/shop_templates.xls", "_blank"); 
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
    .row_title{
        font-size: large;
        margin-bottom: 10px;
        display: inline-block;
        color: rgb(33, 47, 238);
    }
    .el-select{
      width: 100%;
    }
  </style>